package com.example.administrator.futurehope;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.download.ThreadDownloadActivity;
import com.protocol.URLConfig;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity implements
        GestureDetector.OnGestureListener {
    private GestureDetector detector;
    private ViewFlipper flipper;
    private int image_id[] = { R.drawable.photo1, R.drawable.photo2, R.drawable.photo3, R.drawable.photo4};
    private MyListView lv_main;
    private LayoutInflater layoutInflater;
    private LinearLayout ll_point,oaLinearlayout,textLinearlayout;
    private FrameLayout frameLayout;
    private final String msg[] = { "one", "two", "three", "four", "five",
            "six", "seven" };
    private int frameheight;// 图片的高度
    private int window_width;// 屏幕宽度
    private ArrayList<ImageView> imageViews;// ponit 集合
    private ArrayList<View> views;// flipper的孩子
    private Timer timer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 获取屏幕的宽度
        window_width = (int) getResources().getDimension(R.dimen.window_width);
        detector = new GestureDetector(this);
        initView();

        timer = new Timer(true);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        int pageIndex = getPageIndex(flipper.getCurrentView());

                        if (pageIndex == flipper.getChildCount() - 1)
                            pageIndex = 0;
                        else
                            pageIndex++;

                        flipper.setInAnimation(AnimationUtils.loadAnimation(
                                MainActivity.this, R.anim.push_right_in));
                        flipper.setOutAnimation(AnimationUtils.loadAnimation(
                                MainActivity.this, R.anim.push_left_out));
                        flipper.showNext();
                        draw_Point(pageIndex);

                    }
                });
            }
        }, 5000, 5000);

    }


    /***
     * 初始化 point
     */
    void initPoint() {
        imageViews = new ArrayList<ImageView>();
        ImageView imageView;
        for (int i = 0; i < image_id.length; i++) {
            imageView = new ImageView(this);
            imageView.setBackgroundResource(R.drawable.page_indicator);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
                            LayoutParams.WRAP_CONTENT));
            layoutParams.leftMargin = 10;
            layoutParams.rightMargin = 10;
            ll_point.addView(imageView, layoutParams);
            imageViews.add(imageView);
        }
        findView();
        init();
        setLisener();
    }


    private void findView() {
        oaLinearlayout=(LinearLayout)findViewById(R.id.oa_linearLayout);
        textLinearlayout = (LinearLayout)findViewById(R.id.textlinearLayout);
    }

    private void init() {
    }

    private void setLisener() {
        oaLinearlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                   Toast.makeText(MainActivity.this,"OA",Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(MainActivity.this,OaActivity.class);
                startActivity(intent);
            }
        });
        textLinearlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isHave=isAvilible(MainActivity.this,"com.medical.fhuc.fhucmedical_crp");
                if(isHave==true){
                try {
                    Intent mIntent = new Intent("android.intent.action.MAIN");
                    ComponentName comp = new ComponentName("com.medical.fhuc.fhucmedical_crp", "com.medical.fhuc.fhucmedical_crp.LoginActivity");
                    mIntent.setComponent(comp);
                    mIntent.addCategory("android.intent.category.LAUNCHER");
                    startActivity(mIntent);//启动
//                finish();//关闭app
                }catch (Exception e){
                    e.printStackTrace();
                }}else if (isHave==false){

                    Intent intent = new Intent(MainActivity.this, ThreadDownloadActivity.class);
                    intent.putExtra("URL", URLConfig.DOWM_MINSHITIKU);
                    intent.putExtra("fileName", URLConfig.DOWM_APPNAME);
                    startActivity(intent);
                }

            }
        });
    }



    /**
     * 检查手机上是否安装了指定的软件
     * @param context
     * @param packageName：应用包名
     * @return
     */
    public static boolean isAvilible(Context context, String packageName){
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if(packageInfos != null){
            for(int i = 0; i < packageInfos.size(); i++){
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    /***
     * ChildView
     */
    void initChildView(ViewFlipper flipper) {
        views = new ArrayList<View>();
        LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT);
        for (int i = 0; i < image_id.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setScaleType(ScaleType.FIT_XY);
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                    image_id[i]);
            Bitmap bitmap2 = getBitmap(bitmap, window_width);
            frameheight = bitmap2.getHeight();// 获取要显示的高度
            imageView.setImageResource(image_id[i]);
            flipper.addView(imageView, layoutParams);
            views.add(imageView);
        }
        initPoint();
    }

    /***
     * 初始化 HeadImage
     */
    void initHeadImage() {
        layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View headview = layoutInflater.inflate(R.layout.head_image, null);

        flipper = (ViewFlipper) headview.findViewById(R.id.ViewFlipper01);

        ll_point = (LinearLayout) headview
                .findViewById(R.id.layout_circle_images);
        frameLayout = (FrameLayout) headview.findViewById(R.id.fl_main);
        initChildView(flipper);

//        LayoutParams layoutParams = (LayoutParams) frameLayout
//                .getLayoutParams();
//        layoutParams.height = frameheight;
//        frameLayout.setLayoutParams(layoutParams);
        draw_Point(0);// 默认首次进入
        lv_main.addHeaderView(headview);// 要卸载setAdapter前面
        lv_main.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1));

    }

    /***
     * init view
     */
    void initView() {
        setContentView(R.layout.activity_main);
        lv_main = (MyListView) findViewById(R.id.lv_main);
        lv_main.setGestureDetector(detector);// 射入手势
        lv_main.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                if (position != 0)
                    Toast.makeText(MainActivity.this, msg[position - 1], Toast.LENGTH_LONG)
                            .show();
                else {
                    int index = getPageIndex(flipper.getCurrentView());

                }

            }
        });
        lv_main.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                                           int position, long id) {
                Toast.makeText(MainActivity.this, "onItemLongClick", Toast.LENGTH_LONG).show();
                /***
                 * 如果返回true，则item失去光标手从开就不会在执行onclick事件，
                 * 如果返回false则光标还在，手松开会执行onclick事件
                 */
                return true;
            }

        });

        lv_main.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v,
                                            ContextMenuInfo menuInfo) {

            }
        });

        initHeadImage();
    }

    /***
     * 更新选中点
     *
     * @param index
     */
    private void draw_Point(int index) {
        for (int i = 0; i < imageViews.size(); i++) {
            imageViews.get(i).setImageResource(R.drawable.page_indicator);
        }
        imageViews.get(index).setImageResource(
                R.drawable.page_indicator_focused);
    }



    /***
     * 对图片处理
     *
     */
    Bitmap getBitmap(Bitmap bitmap, int width) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scale = (float) width / w;
        // 保证图片不变形.
        matrix.postScale(scale, scale);
        // w,h是原图的属性.
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.e("jj", "MainActivity...onTouchEvent...");
        return super.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.e("jj", "MainActivity...dispatchTouchEvent...");

        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        // 在这里执行图片点击事件.
        int index = getPageIndex(flipper.getCurrentView());
        Toast.makeText(MainActivity.this, "图" + index, Toast.LENGTH_LONG).show();
        return false;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        Log.e("jj", "onDown...");
        // 只有返回true 才会执行onSingleTapUp.
        return true;
    }

    /***
     * 返回当前第几屏
     */
    int getPageIndex(View view) {
        for (int i = 0; i < views.size(); i++) {
            if (view == views.get(i))
                return i;
        }
        return 0;

    }

    /**
     * 监听滑动
     */
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                           float velocityY) {

        int pageIndex = getPageIndex(flipper.getCurrentView());
        // 左划
        if (e1.getX() - e2.getX() > 120) {
            this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_right_in));
            this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_left_out));
            this.flipper.showNext();
            if (pageIndex == flipper.getChildCount() - 1)
                draw_Point(0);
            else
                draw_Point(++pageIndex);
            return true;
            // 右划
        } else if (e1.getX() - e2.getX() < -120) {
            this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_left_in));
            this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_right_out));
            this.flipper.showPrevious();
            if (pageIndex == 0)
                draw_Point(flipper.getChildCount() - 1);
            else
                draw_Point(--pageIndex);
            return true;
        }
        return true;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                            float distanceY) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

}